package com.topisv.tms.service.stock.history;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.hibernate.ejb.criteria.predicate.ComparisonPredicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.stock.history.InvHistory;
import com.topisv.tms.repository.AreaGroupDao;
import com.topisv.tms.repository.EdiGoodsSkuDao;
import com.topisv.tms.repository.stock.history.InvHistoryDao;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.base.BaseService;
import com.topisv.tms.utils.enums.StatusEnums;

@Component
@Transactional(readOnly = true)
public class InvHistoryService extends BaseService{
	
	@Autowired 
	private InvHistoryDao invHistoryDao;
	@Autowired
	private AreaGroupDao areagroupDao;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private EdiGoodsSkuDao ediGoodsSkuDao;
	
	private static final Logger logger = LoggerFactory.getLogger(InvHistoryService.class);
	/**
	 * 分页查询
	 * @param param
	 * @return
	 */
	public Page<InvHistory> loadPageByParam(Map<String, Object> param,int pageNumber, int pageSize) {
		//Sort sort = new Sort(Sort.Direction.ASC,"id") ; 
		Order order = new Order(Direction.DESC,"customer.customerName");
		Order order2 = new Order(Direction.DESC,"warehouse.groupName");
		Order order3 = new Order(Direction.DESC,"InvDate");
		//Sort sort = new Sort(Direction.DESC, "Customers.customerName");
		List<Order> list = new ArrayList<Order>();
		list.add(order);
		list.add(order2);
		list.add(order3);
		Sort sort = new Sort(list);
	    PageRequest pageRequest = new PageRequest(pageNumber-1, pageSize, sort);
	    Specification<InvHistory> spec =this.getWhereClause(param);
	    Page<InvHistory> page = this.invHistoryDao.findAll(spec, pageRequest);
	    List<InvHistory> invHistoryList=page.getContent();
    return page;
	}
	
	/**
	 * 查询条件封装
	 * @param param
	 * @return
	 */
	private Specification<InvHistory> getWhereClause(final Map<String, Object> param) {
		
		return new Specification<InvHistory>(){
			
			@Override
		    public Predicate toPredicate(Root<InvHistory> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
		      Predicate pre = cb.conjunction();
		      ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		      try {
			      //开始时间
		    	  String fromDate= (String) param.get("fromDate");
			      if (fromDate != null) {
			        pre.getExpressions().add(cb.equal(r.<String>get("invDate"), fromDate));
			      }
			      
			      //客户编码(必输)
			      String customer = (String)param.get("customer");
			      pre.getExpressions().add(cb.equal(r.<String>get("customer").get("customerCode"), customer));
			      
			      //sku编码
			      String sku = (String)param.get("sku");
			      if(sku != null && !sku.equals("")){
			    	  pre.getExpressions().add(cb.equal(r.<String>get("sku"), sku));
			      }
			      
			      //仓库编码
			      String warehouse = (String) param.get("warehouse");
		    	  if(StringUtils.isNotBlank(warehouse)){
						pre.getExpressions().add(cb.equal(r.<String>get("warehouse").get("groupCode"), warehouse));
				  }else{
					  List<AreaGroup> warehouseList = null;
					  if (StatusEnums.user_type_customer.getStatus().equals(user.userType)) {
							warehouseList = areaGroupService.loadAreaGroupByAuthority(user, user.customerCode);
						} else if (StatusEnums.user_type_paiu.getStatus().equals(user.userType)) {
					       warehouseList = areaGroupService.findByAreaGroups(user.areagroups);
					  }
					  
					  ComparisonPredicate[] areagroupArray  = new ComparisonPredicate[warehouseList.size()];
					  int j = 0;
					  for(AreaGroup areaGroup:warehouseList){
						  areagroupArray[j] = (ComparisonPredicate) cb.equal(r.get("warehouse").get("groupCode"), areaGroup.getGroupCode());
						  j++;
					  } 
					  pre.getExpressions().add(cb.or(areagroupArray));
				  }
				}
			  catch (Exception e) {
				  e.printStackTrace();
			  }
		      
		      return pre;
		    }
		  };
       }
	
	public List<InvHistory> load(Map<String, Object> searchParams) {
		Specification<InvHistory> spec = this.getWhereClause(searchParams);
		Order order = new Order(Direction.DESC,"customer.customerName");
		Order order2 = new Order(Direction.DESC,"warehouse.groupName");
		Order order3 = new Order(Direction.DESC,"InvDate");
		//Sort sort = new Sort(Direction.DESC, "Customers.customerName");
		List<Order> list = new ArrayList<Order>();
		list.add(order);
		list.add(order2);
		list.add(order3);
		Sort sort = new Sort(list);
		List<InvHistory> invHistoryList = this.invHistoryDao.findAll(spec,sort);
		return invHistoryList;
	}

}
